# Windows Terminal 完整安装和配置脚本
# 作者: Claude Code Assistant
# 版本: 1.0

param(
    [switch]$ForceInstall,
    [switch]$SkipDependencies,
    [switch]$WhatIf
)

# 错误处理
$ErrorActionPreference = "Stop"

# 颜色定义
function Write-ColorOutput($ForegroundColor) {
    param([string]$text)
    Write-Host $text -ForegroundColor $ForegroundColor
}

function Write-Step($step, $description) {
    Write-Host "[$step] " -ForegroundColor Cyan -NoNewline
    Write-Host $description -ForegroundColor White
}

function Write-Success($message) {
    Write-Host "✅ $message" -ForegroundColor Green
}

function Write-Error($message) {
    Write-Host "❌ $message" -ForegroundColor Red
}

function Write-Warning($message) {
    Write-Host "⚠️  $message" -ForegroundColor Yellow
}

function Write-Info($message) {
    Write-Host "ℹ️  $message" -ForegroundColor Blue
}

# 检查管理员权限
function Test-Administrator {
    $currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = [Security.Principal.WindowsPrincipal]$currentUser
    return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}

# 检查网络连接
function Test-NetworkConnection {
    try {
        $testConnection = Test-Connection -ComputerName "www.microsoft.com" -Count 1 -Quiet
        return $testConnection
    } catch {
        return $false
    }
}

# 检查 Windows Terminal 安装状态
function Test-WindowsTerminalInstalled {
    $wtPath = Get-Command wt -ErrorAction SilentlyContinue
    $appxPackage = Get-AppxPackage -Name "Microsoft.WindowsTerminal" -ErrorAction SilentlyContinue
    return ($wtPath -ne $null) -or ($appxPackage -ne $null)
}

# 安装 Windows Terminal
function Install-WindowsTerminal {
    Write-Step 1 "正在安装 Windows Terminal..."

    if (-not (Test-NetworkConnection)) {
        Write-Error "网络连接不可用，无法从 Microsoft Store 安装"
        return $false
    }

    try {
        # 方法1：通过 winget 安装
        $winget = Get-Command winget -ErrorAction SilentlyContinue
        if ($winget) {
            Write-Info "使用 winget 安装..."
            winget install --id=Microsoft.WindowsTerminal -e --silent
            if ($LASTEXITCODE -eq 0) {
                Write-Success "Windows Terminal 安装成功"
                return $true
            }
        }

        # 方法2：通过 Microsoft Store (PowerShell)
        Write-Info "通过 Microsoft Store 安装..."
        $storeApps = @("9N0DX20HK701")  # Windows Terminal Store ID

        foreach ($appId in $storeApps) {
            try {
                Add-AppxPackage -RegisterByFamilyName -MainPackage $appId -ErrorAction Stop
                Write-Success "Windows Terminal 安装成功"
                return $true
            } catch {
                Write-Warning "安装方法失败，尝试其他方法..."
            }
        }

        # 方法3：提示用户手动安装
        Write-Warning "自动安装失败，请手动安装："
        Write-Info "1. 打开 Microsoft Store"
        Write-Info "2. 搜索 'Windows Terminal'"
        Write-Info "3. 点击 '获取' 或 '安装'"
        Write-Info "4. 安装完成后重新运行此脚本"

        return $false
    } catch {
        Write-Error "安装过程中出现错误: $($_.Exception.Message)"
        return $false
    }
}

# 创建 Windows Terminal 配置文件
function Set-WindowsTerminalConfig {
    Write-Step 2 "配置 Windows Terminal 设置..."

    $settingsDir = "$env:LOCALAPPDATA\Packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\LocalState"
    $settingsFile = "$settingsDir\settings.json"
    $backupFile = "$settingsFile.backup.$(Get-Date -Format 'yyyyMMdd_HHmmss')"

    try {
        # 创建目录
        if (-not (Test-Path $settingsDir)) {
            New-Item -ItemType Directory -Path $settingsDir -Force | Out-Null
        }

        # 备份现有配置
        if (Test-Path $settingsFile) {
            Copy-Item $settingsFile $backupFile -Force
            Write-Info "已备份现有配置到: $backupFile"
        }

        # 创建优化的配置
        $config = @{
            "$schema" = "https://raw.githubusercontent.com/microsoft/terminal/main/schemas/profiles.schema.json"
            "defaultProfile" = "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}"
            "copyOnSelect" = $false
            "copyFormatting" = $false
            "profiles" = @{
                "defaults" = @{
                    "fontFace" = "Consolas, 'Courier New'"
                    "fontSize" = 11
                    "fontWeight" = "normal"
                    "colorScheme" = "Campbell"
                    "cursorShape" = "bar"
                    "cursorColor" = "#FFFFFF"
                    "scrollbarVisibility" = "hidden"
                    "background" = "#1E1E1E"
                    "foreground" = "#CCCCCC"
                    "useAcrylic" = $false
                    "padding" = "8, 8, 8, 8"
                    "snapOnInput" = $true
                    "altClickAltGr" = $false
                    "antialiasingMode" = "grayscale"
                    "bellStyle" = "audible"
                    "showTerminalTitleInTitlebar" = $true
                    "experimental.useAtlasEngine" = $false
                }
                "list" = @(
                    @{
                        "guid" = "{61c54bbd-c2c6-5271-96e7-009a87ff44bf}"
                        "name" = "PowerShell"
                        "commandline" = "powershell.exe"
                        "icon" = "ms-appx:///ProfileIcons/{61c54bbd-c2c6-5271-96e7-009a87ff44bf}.png"
                        "hidden" = $false
                        "startingDirectory" = "%USERPROFILE%"
                    },
                    @{
                        "guid" = "{0caa0dad-35be-5f56-a8ff-afceeeaa6101}"
                        "name" = "Command Prompt"
                        "commandline" = "cmd.exe"
                        "icon" = "ms-appx:///ProfileIcons/{0caa0dad-35be-5f56-a8ff-afceeeaa6101}.png"
                        "hidden" = $false
                        "startingDirectory" = "%USERPROFILE%"
                    }
                )
            }
            "schemes" = @()
            "actions" = @(
                @{
                    "command" = "copy"
                    "keys" = "ctrl+c"
                },
                @{
                    "command" = "paste"
                    "keys" = "ctrl+v"
                },
                @{
                    "command" = "find"
                    "keys" = "ctrl+shift+f"
                },
                @{
                    "command" = { "action" = "splitPane", "split" = "vertical" }
                    "keys" = "ctrl+shift+d"
                },
                @{
                    "command" = { "action" = "splitPane", "split" = "horizontal" }
                    "keys" = "ctrl+shift+e"
                },
                @{
                    "command" = { "action" = "newTab" }
                    "keys" = "ctrl+shift+t"
                }
            )
        }

        # 保存配置文件
        $config | ConvertTo-Json -Depth 10 | Out-File -FilePath $settingsFile -Encoding utf8
        Write-Success "Windows Terminal 配置已保存"
        return $true
    } catch {
        Write-Error "配置失败: $($_.Exception.Message)"
        return $false
    }
}

# 设置 PowerShell 配置文件
function Set-PowerShellProfile {
    Write-Step 3 "配置 PowerShell 环境..."

    $profileDir = Split-Path $PROFILE.CurrentUserCurrentHost -Parent
    $profileFile = $PROFILE.CurrentUserCurrentHost
    $backupFile = "$profileFile.backup.$(Get-Date -Format 'yyyyMMdd_HHmmss')"

    try {
        # 创建目录
        if (-not (Test-Path $profileDir)) {
            New-Item -ItemType Directory -Path $profileDir -Force | Out-Null
        }

        # 备份现有配置
        if (Test-Path $profileFile) {
            Copy-Item $profileFile $backupFile -Force
            Write-Info "已备份现有 PowerShell 配置到: $backupFile"
        }

        # 创建优化的 PowerShell 配置
        $profileContent = @'
# PowerShell 配置文件 - Unicode 支持
# 创建时间: $(Get-Date)

# 设置控制台编码为 UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
[Console]::InputEncoding = [System.Text.Encoding]::UTF8

# 设置默认文件编码
$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
$PSDefaultParameterValues['Set-Content:Encoding'] = 'utf8'
$PSDefaultParameterValues['Get-Content:Encoding'] = 'utf8'

# 设置代码页为 UTF-8
try {
    chcp 65001 | Out-Null
} catch {
    # 忽略代码页设置错误
}

# 简单的提示符（避免 Unicode 字符）
function prompt {
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = [Security.Principal.WindowsPrincipal] $identity
    $adminSuffix = ""
    if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
        $adminSuffix = " [ADMIN]"
    }

    $path = $PWD.Path
    if ($path.Length -gt 40) {
        $path = "..." + $path.Substring($path.Length - 37)
    }

    "PS $path$adminSuffix> "
}

# 设置一些有用的别名
Set-Alias -Name "ll" -Value "Get-ChildItem" -Option AllScope -Description "长格式列表"
Set-Alias -Name "la" -Value "Get-ChildItem -Force" -Option AllScope -Description "显示所有文件"
Set-Alias -Name "grep" -Value "Select-String" -Option AllScope -Description "文本搜索"

# 显示欢迎信息
Write-Host "PowerShell with Unicode support loaded." -ForegroundColor Green
Write-Host "Environment: PowerShell $PSVersionTable.PSVersion" -ForegroundColor Blue
Write-Host "Encoding: UTF-8 (65001)" -ForegroundColor Cyan
'@

        # 保存配置文件
        $profileContent | Out-File -FilePath $profileFile -Encoding utf8 -Force
        Write-Success "PowerShell 配置已保存"
        return $true
    } catch {
        Write-Error "PowerShell 配置失败: $($_.Exception.Message)"
        return $false
    }
}

# 测试 Unicode 支持
function Test-UnicodeSupport {
    Write-Step 4 "测试 Unicode 支持..."

    $tests = @(
        @{ "name" = "ASCII"; "text" = "Hello World" },
        @{ "name" = "中文"; "text" = "你好世界" },
        @{ "name" = "日文"; "text" = "こんにちは" },
        @{ "name" = "Emoji"; "text" = "✅ 🎉 🚀" }
    )

    $allPassed = $true

    foreach ($test in $tests) {
        try {
            Write-Host "  Testing $($test.name): " -ForegroundColor Yellow -NoNewline
            Write-Host $test.text -ForegroundColor Green
        } catch {
            Write-Host "  Testing $($test.name): " -ForegroundColor Yellow -NoNewline
            Write-Host "FAILED" -ForegroundColor Red
            $allPassed = $false
        }
    }

    # 测试 Python Unicode 支持
    Write-Host "  Testing Python Unicode: " -ForegroundColor Yellow -NoNewline
    try {
        $pythonTest = python -c "print('Python Unicode: 你好 🎉')" 2>$null
        if ($LASTEXITCODE -eq 0) {
            Write-Host "PASSED" -ForegroundColor Green
        } else {
            Write-Host "Python not found" -ForegroundColor Red
            $allPassed = $false
        }
    } catch {
        Write-Host "Python not found" -ForegroundColor Red
        $allPassed = $false
    }

    return $allPassed
}

# 显示总结和后续步骤
function Show-Summary {
    Write-Host ""
    Write-Host "🎉 Windows Terminal 安装和配置完成！" -ForegroundColor Cyan
    Write-Host ""
    Write-Host "📋 安装摘要:" -ForegroundColor White
    Write-Host "  ✅ Windows Terminal 已安装" -ForegroundColor Green
    Write-Host "  ✅ UTF-8 编码已配置" -ForegroundColor Green
    Write-Host "  ✅ PowerShell 配置已优化" -ForegroundColor Green
    Write-Host "  ✅ Unicode 支持已测试" -ForegroundColor Green
    Write-Host ""
    Write-Host "🚀 如何使用:" -ForegroundColor White
    Write-Host "  1. 按 Win+R，输入 'wt' 启动 Windows Terminal" -ForegroundColor Yellow
    Write-Host "  2. 测试: python -c \"print('✅ 你好!')\"" -ForegroundColor Yellow
    Write-Host "  3. 享受现代化的终端体验！" -ForegroundColor Yellow
    Write-Host ""
    Write-Host "💡 常用快捷键:" -ForegroundColor White
    Write-Host "  • Ctrl+Shift+T: 新建标签页" -ForegroundColor Blue
    Write-Host "  • Ctrl+Shift+D: 垂直分屏" -ForegroundColor Blue
    Write-Host "  • Ctrl+Shift+E: 水平分屏" -ForegroundColor Blue
    Write-Host "  • Ctrl+C/Ctrl+V: 复制/粘贴" -ForegroundColor Blue
    Write-Host "  • Ctrl+,: 打开设置" -ForegroundColor Blue
    Write-Host ""
    Write-Host "🔧 如果需要重新配置，请运行此脚本。" -ForegroundColor Cyan
    Write-Host ""
}

# 主程序
function Main {
    Write-Host "🚀 Windows Terminal 安装和配置工具" -ForegroundColor Cyan
    Write-Host "========================================" -ForegroundColor White
    Write-Host ""

    # 检查系统要求
    Write-Step 0 "检查系统要求..."

    if (-not (Test-Administrator)) {
        Write-Warning "建议以管理员身份运行此脚本以获得最佳体验"
    }

    if (-not (Test-NetworkConnection) -and -not (Test-WindowsTerminalInstalled)) {
        Write-Error "网络连接不可用，无法安装 Windows Terminal"
        return 1
    }

    Write-Info "系统要求检查通过"
    Write-Host ""

    # 检查是否已安装
    if (Test-WindowsTerminalInstalled) {
        Write-Success "Windows Terminal 已安装"
    } elseif ($ForceInstall) {
        Write-Warning "强制安装模式：重新安装 Windows Terminal"
        $installResult = Install-WindowsTerminal
        if (-not $installResult) {
            Write-Error "Windows Terminal 安装失败"
            return 1
        }
    } else {
        Write-Warning "Windows Terminal 未安装"
        $installResult = Install-WindowsTerminal
        if (-not $installResult) {
            Write-Error "Windows Terminal 安装失败"
            return 1
        }
    }

    # 配置 Windows Terminal
    $configResult = Set-WindowsTerminalConfig
    if (-not $configResult) {
        Write-Error "Windows Terminal 配置失败"
        return 1
    }

    # 配置 PowerShell
    $profileResult = Set-PowerShellProfile
    if (-not $profileResult) {
        Write-Error "PowerShell 配置失败"
        return 1
    }

    # 测试 Unicode 支持
    $unicodeResult = Test-UnicodeSupport
    if (-not $unicodeResult) {
        Write-Warning "Unicode 测试部分失败，但不影响正常使用"
    }

    # 显示总结
    Show-Summary

    return 0
}

# 运行主程序
try {
    $exitCode = Main
    exit $exitCode
} catch {
    Write-Error "脚本执行失败: $($_.Exception.Message)"
    exit 1
}